package com.pithypan.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.security.cert.TrustAnchor;
import java.util.concurrent.TimeUnit;

/**
 * redis工具类
 * @param <v>
 */
@Component
public class RedisUtils<v> {

    @Resource
    private RedisTemplate<String, v> redisTemplate;

    private static final Logger logger = LoggerFactory.getLogger(RedisUtils.class);


    /**
     *
     * 通过key获取值
     * @param key
     * @return
     */
    public v get(String key) {
        return key == null ? null : redisTemplate.opsForValue().get(key);
    }


    /**
     * 普通缓存
     * @param key
     * @param value
     * @return
     */
    public boolean set(String key, v value) {
        try {
            redisTemplate.opsForValue().set(key, value);
            return true;
        } catch (Exception e) {
            logger.error("设置redis---key: {}, value: {}  失败", key, value);
            return false;
        }
    }


    /**
     * 普通缓存，并设置有效期
     * @param key
     * @param value
     * @param time
     * @return
     */
    public boolean setex(String key, v value, long time) {
        try {
            if (time > 0) {
                redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
            } else {
                set(key, value);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("设置redis---key: {}, value: {}  失败", key, value);
            return false;
        }
    }
}
